"""
自定义元类

核心知识点：
    1.类也是对象，type是创建类的类
    2.元类是创建类的类，type -> class(对象) -> 对象
    3.元类可以控制类实例化的过程
    4.python中类的实例化过程，会首先寻找metaclass，通过metaclass去创建user类，再去创建实例
"""


def create_class(name):
    if name == "user":
        class User:
            def __str__(self):
                return "user"

        return User

    elif name == "company":
        class Company:
            def __str__(self):
                return "company"

        return Company


def say(self):
    return "i am kevin"


class BaseClass():
    def answer(self):
        return "i am baseclass"


# 动态创建类
User = type("User", (BaseClass,), {"name": "kevin", "say": say})


def use_class():
    my_class = create_class("user")
    my_obj = my_class()
    print(my_obj)
    # 输出结果：
    """
    user
    """

    # 动态创建类
    user = User()
    print(user)
    print(user.name)
    print(user.say())
    print(user.answer())
    # 输出结果：
    """
    <__main__.User object at 0x10a1aa128>
    kevin
    i am kevin
    i am baseclass
    """


class MetaClass(type):
    """
    可以在元类中做事先工作（如检查）
    """

    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, *args, **kwargs)


class Student(metaclass=MetaClass):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name


def use_student():
    student = Student(name="Kevin")
    print(student)
    # 输出结果：
    """
    Kevin
    """


if __name__ == '__main__':
    use_class()
    use_student()
